package com.yyg.wiki.service;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyg.wiki.domain.Ebook;
import com.yyg.wiki.domain.EbookExample;
import com.yyg.wiki.mapper.EbookMapper;
import com.yyg.wiki.req.EbookQueryReq;
import com.yyg.wiki.req.EbookSaveReq;
import com.yyg.wiki.resp.EbookQueryResp;
import com.yyg.wiki.resp.PageResp;
import com.yyg.wiki.util.CopyUtil;
import com.yyg.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * ClassName: EbookService
 * Description:
 * date: 2021/7/22 15:00
 *
 * @author 17878
 * @since JDK 1.8
 */
@Service
public class EbookService {
    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;
    private static final Logger LOG = LoggerFactory.getLogger(EbookService.class);


    public PageResp<EbookQueryResp> list(EbookQueryReq Req){

        PageHelper.startPage(Req.getPage(),Req.getSize());
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();

        if (!ObjectUtils.isEmpty(Req.getName())){
            criteria.andNameLike("%"+Req.getName()+"%");
        }
        if (!ObjectUtils.isEmpty(Req.getCategoryId2())){
            criteria.andCategory2IdEqualTo(Req.getCategoryId2());
        }

        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());
//        List<EbookResp> respList=new ArrayList<>();
//        for (Ebook ebook : ebookList) {
//
//            EbookResp ebookResp = CopyUtil.copy(ebook, EbookResp.class);
//            respList.add(ebookResp);
//        }
        List<EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     *
     * 功能描述:新增操作
     *
     * @param:
     * @return:
     * @auther: 17878
     * @date: 2021/7/29 15:14
     */
    public void save(EbookSaveReq req){
        System.out.println("genggaikkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"+req);
        Ebook ebook=CopyUtil.copy(req,Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())){
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        }else {
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
